from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.future import select
from sqlalchemy import update, delete
from database import get_db
from models import Note   # 需要新建 Note 模型
from pydantic import BaseModel

router = APIRouter(prefix="/notes", tags=["Notes"])

# --- 请求/响应模型 ---
class NoteCreate(BaseModel):
    title: str
    content: str

class NoteUpdate(BaseModel):
    title: str | None = None
    content: str | None = None

class NoteOut(BaseModel):
    id: int
    title: str
    content: str

# --- CRUD 接口 ---

# 1. 创建
@router.post("/", response_model=NoteOut)
async def create_note(note: NoteCreate, db: AsyncSession = Depends(get_db)):
    new_note = Note(title=note.title, content=note.content)
    db.add(new_note)
    await db.commit()
    await db.refresh(new_note)
    return new_note

# 2. 查询全部
@router.get("/", response_model=list[NoteOut])
async def read_notes(db: AsyncSession = Depends(get_db)):
    res = await db.execute(select(Note))
    return res.scalars().all()

# 3. 查询单条
@router.get("/{note_id}", response_model=NoteOut)
async def read_note(note_id: int, db: AsyncSession = Depends(get_db)):
    res = await db.execute(select(Note).where(Note.id == note_id))
    note = res.scalar_one_or_none()
    if not note:
        raise HTTPException(404, "Note not found")
    return note

# 4. 修改
@router.put("/{note_id}", response_model=NoteOut)
async def update_note(
    note_id: int,
    payload: NoteUpdate,
    db: AsyncSession = Depends(get_db)
):
    stmt = (
        update(Note)
        .where(Note.id == note_id)
        .values(**{k: v for k, v in payload.dict(exclude_unset=True).items()})
        .execution_options(synchronize_session="fetch")
    )
    await db.execute(stmt)
    await db.commit()
    return await read_note(note_id, db)

# 5. 删除
@router.delete("/{note_id}", response_model=dict)
async def delete_note(note_id: int, db: AsyncSession = Depends(get_db)):
    stmt = delete(Note).where(Note.id == note_id)
    res = await db.execute(stmt)
    await db.commit()
    if res.rowcount == 0:
        raise HTTPException(404, "Note not found")
    return {"ok": True}